iT邦幫忙

2022 iThome 鐵人賽

DAY 11
0

前言:

這是一個在Expo專案內使用Barcode 模組的範例
我學React Native的目標就是做一個進銷存的APP
條碼掃描的功能是必須的,今天這個範例讓我離目標更進一步

程式畫面預覽:

圖1

範例影片:

影片

程式碼:

import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';

export default function App() {

  const [hasPermission, setHasPermission] = useState(null)
  const [scanned, setScanned] = useState(false)
  const [text, setText] = useState("Not yet scanned!")

  const askForCameraPermission = () => {
    (async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === "granted")
    })()
  }

  //  Request 相機使用權限
  useEffect(() => {
    askForCameraPermission()
  }, []);

  // 掃描處理區塊
  const handleBarCodeScanned = ({ type, data }) => {
    setScanned(true);
    setText(data);
    console.log("type: " + type + "\nData: " + data);

  }

  // 檢查權限 & 畫面渲染
  if (hasPermission === null) {
    return (
      <View style={styles.container}>
        <Text>Requesting for Camera permission!</Text>
      </View>
    )
  } else if (hasPermission === false) {
    return (
      <View style={styles.container}>
        <Text style={{ margin: 10 }}>No access to camera</Text>
        <Button title={'Allow Camera'} onPress={() => askForCameraPermission()} />
      </View>)
  }

  // main view
  return (
    <View style={styles.container}>
      <View style={styles.barCodeBox}>
        <BarCodeScanner
          onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
          style={{ width: 400, height: 400, }}
        />

      </View>
      <Text style={styles.mainText}>{text}</Text>
      {scanned && <Button title={"Scanned again"} color="tomato" onPress={() => setScanned(false)} />}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  barCodeBox: {
    backgroundColor: "tomato",
    alignItems: "center",
    justifyContent: "center",
    width: 300,
    height: 300,
    overflow: "hidden",
    borderRadius: 30,
  },
  mainText: {
    fontSize: 16,
    margin: 20,
  }
});

範例 Source Code:

git clone https://smilehsu@bitbucket.org/smilehsu/yt_example_barcode0119.git

參考資料:

  1. QR & Barcode Scanner App Tutorial in React Native
  2. Expo-BarCodeScanner

上一篇
DAY10 - 看YT學React Native - 使用相機模組(Camera)
下一篇
DAY12 - 看YT學React Native - UI 範例1
系列文
總是學不來的中年大叔,孤獨的自學之旅第二年30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言